/*
 * Copyright (c) 2008-2010.
 *
 * This software is ......
 */
package com.jinmei.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONUtils;


/**
 * This JsonUtil is a UTIL tool class for all the AJAX request.
 *
 * @Id JsonUtil.java
 * @version
 * @author @Date Mar 27, 2009
 */
public class JsonUtil {
  
	/** singleInstance */
	private static JsonUtil singleInstance;

	/**
	 * Convert the string data to JSON style.
	 * 
	 * @param result
	 * @return
	 */
	public static String toJsonString(AjaxResult result) {
		return singleInstance.generateJsonString(result);
	}
	
	/**
	 * Convert the data object to JSON style. 
	 * 
	 * @param data
	 * @return
	 */
	public static String toJsonObjectString(Object data) {
		return singleInstance.generateJsonObject(data);
	}	
	
	/**
	 * Wrapped the array object to JSON style.
	 * 
	 * 
	 * @param arrayObject
	 * @return
	 */
	public static String toJsonArrayString(Object arrayObject) {
		return singleInstance.generateJsonArray(arrayObject);
	}
	
	/** JsonConfig contains others processors which want to affect on the JSON string.*/
	private JsonConfig jsonConfig = new JsonConfig();	
	
	/**
	 * @param result
	 * @return
	 */
	public String generateJsonString(AjaxResult result) {
		switch(result.getRequestType()) {
		case AjaxResult.AJAX_SUBMIT:
			return JSONObject.fromObject(result, jsonConfig).toString();
		case AjaxResult.AJAX_DATA:
			if(JSONUtils.isArray(result.getData())) {
				return JSONArray.fromObject(result.getData(), jsonConfig).toString();
			}
			return JSONObject.fromObject(result.getData(), jsonConfig).toString();
		default:
			throw new RuntimeException(result.toString());
		}
	}
	
	/**	
	 * @param data
	 * @return
	 */
	public String generateJsonObject(Object data) {
		return JSONObject.fromObject(data, jsonConfig).toString();
	}
	
	/**	
	 * @param 
	 * @return
	 */
	public String generateJsonArray(Object arrayObject) {
		return JSONArray.fromObject(arrayObject, jsonConfig).toString();
	}

	public void init() throws Exception {		
		if(JsonUtil.singleInstance == null) {
			JsonUtil.singleInstance = this;
		}
	}
}